# -*- coding: utf-8 -*-

from django.test import TestCase

from aio.models import Draw, Player
from aio.appl_bij import ApplBij
from aio.views import _correlation_matrix

import time

class ApplBijTest(TestCase):
    
    def setUp(self):
        pass
    
    def tearDown(self):
        pass

    def test_unsafe(self):

        size = 4
        corr = [[True for j in range(2*size)] for i in range(2*size)]

        for i in range(len(corr)/2):
            for j in range(2*i, 2*i+2):
                corr[2*i+1][j] = corr[2*i][j] = False

        self._print_matrix(corr)
        # Creamos una aplicación biyectiva a partir de la matriz A.
        # (La inicializamos en modo 'UNSAFE').
        appl=ApplBij(corr, 'UNSAFE')

        # Determinamos el tamaño del bucle de búsqueda.
        loopSize=appl.GetLoopSize()

        # Buscamos e imprimimos los sorteos exitosos.
        for i in range(2):
            result=appl.GetRandomApplBij(loopSize)
            print 'Resultado del sorteo %d' % i
            print result
            time.sleep(1)
    
    def test_sorteo(self):
        print 'test_sorteo'
        draw = Draw(subject="Asunto", body="Cuerpo", language="es_es")
        players = []
        for i in range(6):
            pl = Player(name="nombre_%d" % i, email="email@aio.com", domain="aio.com", draw=draw, pwd="1234")
            pl.drawid = i
            players.append(pl)
            
        exclusions = {0:[1,2], 1:[0,3], 2:[3], 3:[2], 4:[0,1,5], 5:[3,4]}
        corr = _correlation_matrix(players, exclusions) 

        self._print_matrix(corr)

        appl=ApplBij(corr, 'UNSAFE')
        loopSize=appl.GetLoopSize()
        for k in range(10):
            result=appl.GetRandomApplBij(loopSize)
            print result
            self._check_valid_result(exclusions, result)
            

    def _check_valid_result(self, exclusions, result):
        for i in range(len(result)):
            excs = exclusions.get(i,[])
            if result[i] in excs:
                print "ERROR. Player %d can not be friend with %d!" % (i, result[i])
                exit(0)
        print "sorteo OK"
        
        
    def _print_matrix(self, corr):
        # Imprimimos la matriz corr.
        print 'Sorteos del Amigo invisible para %d parejas' % int(len(corr)/2)
        print
        for i in range(len(corr)):
            print '%-5d' % i,
        print
        
        for i in range(len(corr)):
            for j in range(len(corr[0])):
                print '%-5s' % str(corr[i][j]),
            print
        